<?php
require_once 'includes/header.php';
require_once 'includes/DatabaseHelper.php';
require_once 'includes/functions.php';

$db = Database::getInstance();

// 初始化变量
$gameId = isset($_GET['game_id']) ? (int)$_GET['game_id'] : 0;
$game = null;
$errors = [];
$success = '';

// 检查游戏是否存在
if ($gameId > 0) {
    $game = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "games WHERE id = ?", [$gameId]);
    
    if (!$game) {
        $_SESSION['flash_message'] = '游戏不存在';
        $_SESSION['flash_type'] = 'danger';
        header('Location: games.php');
        exit;
    }
}

// 创建资源目录
$resourcesDir = '../uploads/games/' . $gameId . '/';
if (!is_dir($resourcesDir)) {
    mkdir($resourcesDir, 0755, true);
}

// 处理资源上传
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理图片资源上传
    if (isset($_FILES['game_images']) && !empty($_FILES['game_images']['name'][0])) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $maxSize = 2 * 1024 * 1024; // 2MB
        
        for ($i = 0; $i < count($_FILES['game_images']['name']); $i++) {
            if ($_FILES['game_images']['error'][$i] === UPLOAD_ERR_OK) {
                $tmpName = $_FILES['game_images']['tmp_name'][$i];
                $originalName = $_FILES['game_images']['name'][$i];
                $fileSize = $_FILES['game_images']['size'][$i];
                $fileType = $_FILES['game_images']['type'][$i];
                
                // 验证文件类型和大小
                if (!in_array($fileType, $allowedTypes)) {
                    $errors[] = "文件 {$originalName} 类型不允许，仅支持JPG、PNG、GIF和WEBP格式";
                    continue;
                }
                
                if ($fileSize > $maxSize) {
                    $errors[] = "文件 {$originalName} 超过大小限制，最大2MB";
                    continue;
                }
                
                // 生成唯一文件名
                $extension = pathinfo($originalName, PATHINFO_EXTENSION);
                $newFileName = 'image_' . uniqid() . '.' . $extension;
                $destination = $resourcesDir . 'images/';
                
                if (!is_dir($destination)) {
                    mkdir($destination, 0755, true);
                }
                
                $filePath = $destination . $newFileName;
                
                if (move_uploaded_file($tmpName, $filePath)) {
                    // 记录上传成功的文件
                    $relativePath = 'uploads/games/' . $gameId . '/images/' . $newFileName;
                    
                    // 如果这是第一张图片并且游戏尚未有主图，将其设为主图
                    if (empty($game['image']) && $i === 0) {
                        $db->update('games', ['image' => $relativePath], 'id = ?', [$gameId]);
                    }
                    
                    // 在数据库中记录资源（可以创建一个新表存储游戏资源）
                    $resourceData = [
                        'game_id' => $gameId,
                        'type' => 'image',
                        'filename' => $originalName,
                        'file_path' => $relativePath,
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    
                    // 检查是否存在game_resources表，如果不存在，在此处创建
                    try {
                        $db->query("SELECT 1 FROM " . DB_PREFIX . "game_resources LIMIT 1");
                    } catch (Exception $e) {
                        // 表不存在，创建表
                        $db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "game_resources` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `game_id` int(11) NOT NULL,
                            `type` varchar(20) NOT NULL,
                            `filename` varchar(255) NOT NULL,
                            `file_path` varchar(255) NOT NULL,
                            `created_at` datetime NOT NULL,
                            PRIMARY KEY (`id`),
                            KEY `game_id` (`game_id`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                    }
                    
                    $db->insert('game_resources', $resourceData);
                    $success = "资源上传成功！";
                } else {
                    $errors[] = "上传文件 {$originalName} 失败";
                }
            } else {
                $errors[] = "上传文件时出错，错误代码: " . $_FILES['game_images']['error'][$i];
            }
        }
    }
    
    // 处理音频资源上传
    if (isset($_FILES['game_audio']) && !empty($_FILES['game_audio']['name'][0])) {
        $allowedTypes = ['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/mp3'];
        $maxSize = 5 * 1024 * 1024; // 5MB
        
        for ($i = 0; $i < count($_FILES['game_audio']['name']); $i++) {
            if ($_FILES['game_audio']['error'][$i] === UPLOAD_ERR_OK) {
                $tmpName = $_FILES['game_audio']['tmp_name'][$i];
                $originalName = $_FILES['game_audio']['name'][$i];
                $fileSize = $_FILES['game_audio']['size'][$i];
                $fileType = $_FILES['game_audio']['type'][$i];
                
                // 验证文件类型和大小
                if (!in_array($fileType, $allowedTypes)) {
                    $errors[] = "文件 {$originalName} 类型不允许，仅支持MP3、WAV和OGG格式";
                    continue;
                }
                
                if ($fileSize > $maxSize) {
                    $errors[] = "文件 {$originalName} 超过大小限制，最大5MB";
                    continue;
                }
                
                // 生成唯一文件名
                $extension = pathinfo($originalName, PATHINFO_EXTENSION);
                $newFileName = 'audio_' . uniqid() . '.' . $extension;
                $destination = $resourcesDir . 'audio/';
                
                if (!is_dir($destination)) {
                    mkdir($destination, 0755, true);
                }
                
                $filePath = $destination . $newFileName;
                
                if (move_uploaded_file($tmpName, $filePath)) {
                    // 记录上传成功的文件
                    $relativePath = 'uploads/games/' . $gameId . '/audio/' . $newFileName;
                    
                    // 在数据库中记录资源
                    $resourceData = [
                        'game_id' => $gameId,
                        'type' => 'audio',
                        'filename' => $originalName,
                        'file_path' => $relativePath,
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    
                    $db->insert('game_resources', $resourceData);
                    $success = "资源上传成功！";
                } else {
                    $errors[] = "上传文件 {$originalName} 失败";
                }
            } else {
                $errors[] = "上传文件时出错，错误代码: " . $_FILES['game_audio']['error'][$i];
            }
        }
    }
    
    // 处理配置文件上传
    if (isset($_FILES['game_config']) && $_FILES['game_config']['error'] === UPLOAD_ERR_OK) {
        $tmpName = $_FILES['game_config']['tmp_name'];
        $originalName = $_FILES['game_config']['name'];
        $fileSize = $_FILES['game_config']['size'];
        
        // 验证文件类型和大小
        $allowedExtensions = ['json', 'xml', 'csv'];
        $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
        
        if (!in_array($extension, $allowedExtensions)) {
            $errors[] = "配置文件类型不允许，仅支持JSON、XML和CSV格式";
        } else {
            // 生成唯一文件名
            $newFileName = 'config_' . uniqid() . '.' . $extension;
            $destination = $resourcesDir . 'config/';
            
            if (!is_dir($destination)) {
                mkdir($destination, 0755, true);
            }
            
            $filePath = $destination . $newFileName;
            
            if (move_uploaded_file($tmpName, $filePath)) {
                // 记录上传成功的文件
                $relativePath = 'uploads/games/' . $gameId . '/config/' . $newFileName;
                
                // 在数据库中记录资源
                $resourceData = [
                    'game_id' => $gameId,
                    'type' => 'config',
                    'filename' => $originalName,
                    'file_path' => $relativePath,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                
                $db->insert('game_resources', $resourceData);
                $success = "资源上传成功！";
            } else {
                $errors[] = "上传配置文件失败";
            }
        }
    }
}

// 获取已上传的资源列表
$resources = $db->fetchAll(
    "SELECT * FROM " . DB_PREFIX . "game_resources WHERE game_id = ? ORDER BY created_at DESC", 
    [$gameId]
);

// 按类型分组资源
$imageResources = [];
$audioResources = [];
$configResources = [];

foreach ($resources as $resource) {
    switch ($resource['type']) {
        case 'image':
            $imageResources[] = $resource;
            break;
        case 'audio':
            $audioResources[] = $resource;
            break;
        case 'config':
            $configResources[] = $resource;
            break;
    }
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1><i class="bi bi-archive"></i> 游戏资源管理</h1>
    <div>
        <a href="game_edit.php?id=<?php echo $gameId; ?>" class="btn btn-primary">
            <i class="bi bi-pencil"></i> 编辑游戏信息
        </a>
        <a href="game_preview.php?id=<?php echo $gameId; ?>" class="btn btn-success">
            <i class="bi bi-eye"></i> 预览游戏
        </a>
        <a href="games.php" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> 返回游戏列表
        </a>
    </div>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <h5>上传出现错误:</h5>
        <ul class="mb-0">
            <?php foreach ($errors as $error): ?>
                <li><?php echo $error; ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div class="alert alert-success">
        <?php echo $success; ?>
    </div>
<?php endif; ?>

<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-info-circle"></i> 游戏信息
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-3">
                <?php if (!empty($game['image'])): ?>
                    <img src="<?php echo '../' . htmlspecialchars($game['image']); ?>" alt="游戏图片" class="img-fluid rounded">
                <?php else: ?>
                    <div class="text-center p-4 bg-light rounded">
                        <i class="bi bi-image fs-1"></i>
                        <p class="mt-2">暂无游戏图片</p>
                    </div>
                <?php endif; ?>
            </div>
            <div class="col-md-9">
                <h3><?php echo htmlspecialchars($game['name']); ?></h3>
                <p class="text-muted"><?php echo htmlspecialchars($game['category']); ?> | 
                   难度: <?php echo str_repeat('★', $game['difficulty']) . str_repeat('☆', 5 - $game['difficulty']); ?> | 
                   年龄: <?php echo $game['min_age'] . '-' . $game['max_age']; ?>岁
                </p>
                <p><?php echo nl2br(htmlspecialchars($game['description'])); ?></p>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- 图片资源上传 -->
    <div class="col-md-4 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <i class="bi bi-image"></i> 上传游戏图片
            </div>
            <div class="card-body">
                <form action="" method="post" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="game_images" class="form-label">选择图片文件</label>
                        <input type="file" class="form-control" id="game_images" name="game_images[]" accept="image/*" multiple>
                        <div class="form-text">支持JPG、PNG、GIF和WEBP格式，最大2MB，可多选</div>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-upload"></i> 上传图片
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 音频资源上传 -->
    <div class="col-md-4 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <i class="bi bi-music-note-beamed"></i> 上传游戏音频
            </div>
            <div class="card-body">
                <form action="" method="post" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="game_audio" class="form-label">选择音频文件</label>
                        <input type="file" class="form-control" id="game_audio" name="game_audio[]" accept="audio/*" multiple>
                        <div class="form-text">支持MP3、WAV和OGG格式，最大5MB，可多选</div>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-upload"></i> 上传音频
                    </button>
                </form>
            </div>
        </div>
    </div>
    
    <!-- 配置文件上传 -->
    <div class="col-md-4 mb-4">
        <div class="card h-100">
            <div class="card-header">
                <i class="bi bi-gear"></i> 上传配置文件
            </div>
            <div class="card-body">
                <form action="" method="post" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label for="game_config" class="form-label">选择配置文件</label>
                        <input type="file" class="form-control" id="game_config" name="game_config" accept=".json,.xml,.csv">
                        <div class="form-text">支持JSON、XML和CSV格式</div>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-upload"></i> 上传配置
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 资源管理 -->
<div class="card mb-4">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs" id="resourceTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="images-tab" data-bs-toggle="tab" data-bs-target="#images" type="button" role="tab" aria-controls="images" aria-selected="true">
                    <i class="bi bi-image"></i> 图片资源 (<?php echo count($imageResources); ?>)
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="audio-tab" data-bs-toggle="tab" data-bs-target="#audio" type="button" role="tab" aria-controls="audio" aria-selected="false">
                    <i class="bi bi-music-note-beamed"></i> 音频资源 (<?php echo count($audioResources); ?>)
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="config-tab" data-bs-toggle="tab" data-bs-target="#config" type="button" role="tab" aria-controls="config" aria-selected="false">
                    <i class="bi bi-gear"></i> 配置文件 (<?php echo count($configResources); ?>)
                </button>
            </li>
        </ul>
    </div>
    <div class="card-body">
        <div class="tab-content" id="resourceTabsContent">
            <!-- 图片资源列表 -->
            <div class="tab-pane fade show active" id="images" role="tabpanel" aria-labelledby="images-tab">
                <?php if (empty($imageResources)): ?>
                    <div class="alert alert-info">
                        尚未上传图片资源
                    </div>
                <?php else: ?>
                    <div class="row row-cols-1 row-cols-md-4 g-4">
                        <?php foreach ($imageResources as $resource): ?>
                            <div class="col">
                                <div class="card h-100">
                                    <img src="<?php echo '../' . $resource['file_path']; ?>" class="card-img-top" alt="<?php echo htmlspecialchars($resource['filename']); ?>" style="height: 200px; object-fit: cover;">
                                    <div class="card-body">
                                        <h5 class="card-title"><?php echo htmlspecialchars($resource['filename']); ?></h5>
                                        <p class="card-text small">
                                            <i class="bi bi-calendar"></i> <?php echo date('Y-m-d H:i', strtotime($resource['created_at'])); ?>
                                        </p>
                                    </div>
                                    <div class="card-footer">
                                        <div class="btn-group btn-group-sm w-100">
                                            <a href="<?php echo '../' . $resource['file_path']; ?>" class="btn btn-outline-primary" target="_blank">
                                                <i class="bi bi-eye"></i> 查看
                                            </a>
                                            <a href="game_resources.php?game_id=<?php echo $gameId; ?>&delete=<?php echo $resource['id']; ?>&type=image" class="btn btn-outline-danger" onclick="return confirm('确定要删除此资源吗？')">
                                                <i class="bi bi-trash"></i> 删除
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- 音频资源列表 -->
            <div class="tab-pane fade" id="audio" role="tabpanel" aria-labelledby="audio-tab">
                <?php if (empty($audioResources)): ?>
                    <div class="alert alert-info">
                        尚未上传音频资源
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>文件名</th>
                                    <th>上传时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($audioResources as $resource): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($resource['filename']); ?></td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($resource['created_at'])); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <audio controls style="height: 30px;">
                                                    <source src="<?php echo '../' . $resource['file_path']; ?>" type="audio/mpeg">
                                                    您的浏览器不支持音频播放
                                                </audio>
                                                <a href="<?php echo '../' . $resource['file_path']; ?>" class="btn btn-outline-primary" download>
                                                    <i class="bi bi-download"></i> 下载
                                                </a>
                                                <a href="game_resources.php?game_id=<?php echo $gameId; ?>&delete=<?php echo $resource['id']; ?>&type=audio" class="btn btn-outline-danger" onclick="return confirm('确定要删除此资源吗？')">
                                                    <i class="bi bi-trash"></i> 删除
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- 配置文件列表 -->
            <div class="tab-pane fade" id="config" role="tabpanel" aria-labelledby="config-tab">
                <?php if (empty($configResources)): ?>
                    <div class="alert alert-info">
                        尚未上传配置文件
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead>
                                <tr>
                                    <th>文件名</th>
                                    <th>上传时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($configResources as $resource): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($resource['filename']); ?></td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($resource['created_at'])); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="<?php echo '../' . $resource['file_path']; ?>" class="btn btn-outline-primary" target="_blank">
                                                    <i class="bi bi-eye"></i> 查看
                                                </a>
                                                <a href="<?php echo '../' . $resource['file_path']; ?>" class="btn btn-outline-success" download>
                                                    <i class="bi bi-download"></i> 下载
                                                </a>
                                                <a href="game_resources.php?game_id=<?php echo $gameId; ?>&delete=<?php echo $resource['id']; ?>&type=config" class="btn btn-outline-danger" onclick="return confirm('确定要删除此资源吗？')">
                                                    <i class="bi bi-trash"></i> 删除
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- 资源删除处理 -->
<?php
if (isset($_GET['delete']) && isset($_GET['type'])) {
    $resourceId = (int)$_GET['delete'];
    $resourceType = $_GET['type'];
    
    // 获取资源信息
    $resource = $db->fetchRow("SELECT * FROM " . DB_PREFIX . "game_resources WHERE id = ? AND game_id = ?", [$resourceId, $gameId]);
    
    if ($resource) {
        // 删除文件
        $filePath = '../' . $resource['file_path'];
        if (file_exists($filePath)) {
            @unlink($filePath);
        }
        
        // 如果是主图，清除游戏表中的主图字段
        if ($resourceType === 'image' && $game['image'] === $resource['file_path']) {
            $db->update('games', ['image' => ''], 'id = ?', [$gameId]);
        }
        
        // 从数据库中删除记录
        $db->delete('game_resources', 'id = ?', [$resourceId]);
        
        $_SESSION['flash_message'] = '资源已成功删除';
        $_SESSION['flash_type'] = 'success';
    } else {
        $_SESSION['flash_message'] = '资源不存在或不属于此游戏';
        $_SESSION['flash_type'] = 'danger';
    }
    
    // 重定向，防止重复删除
    header('Location: game_resources.php?game_id=' . $gameId);
    exit;
}
?>

<!-- 引入Bootstrap JavaScript和依赖 -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>

<?php
require_once 'includes/footer.php';
?> 